package org.example.src.controller;

import org.example.src.dto.request.LoginRequest;
import org.example.src.dto.request.RegisterRequest;
import org.example.src.dto.response.ApiResponse;
import org.example.src.dto.response.LoginResponse;
import org.example.src.entity.User;
import org.example.src.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "*")
public class AuthController extends BaseController {

    @Autowired
    private AuthService authService;

    @PostMapping("/login")
    public ResponseEntity<ApiResponse<LoginResponse>> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            LoginResponse response = authService.login(loginRequest);
            return success("登录成功", response);
        } catch (Exception e) {
            return error("登录失败: " + e.getMessage());
        }
    }

    @PostMapping("/register")
    public ResponseEntity<ApiResponse<User>> register(@Valid @RequestBody RegisterRequest registerRequest) {
        try {
            User user = authService.register(registerRequest);
            return created(user);
        } catch (Exception e) {
            return error("注册失败: " + e.getMessage());
        }
    }
}
